<?php

namespace App\Policies;

use App\Models\User;
use App\Models\Plan;
use Illuminate\Auth\Access\HandlesAuthorization;

class PlanPolicy
{
    use HandlesAuthorization;

    /**
     * 查看拍摄
     * @param User $user
     * @param Plan $plan
     * @return bool
     */
    public function view(User $user, Plan $plan): bool
    {
        if ($user->isAdmin() || $user->id === $plan->user_id) {
            return true;
        }

        $exists = $plan->users->filter(function ($val) use ($user) {
            return $user->id === $val->id;
        });

        return $exists->isNotEmpty();
    }

    /**
     * 编辑拍摄
     * @param User $user
     * @param Plan $plan
     * @return bool
     */
    public function update(User $user, Plan $plan): bool
    {
        return $user->isAdmin() || $user->id === $plan->user_id;
    }

    /**
     * 拍摄原图加入/取消精修
     * @param User $user
     * @param Plan $plan
     * @return bool
     */
    public function toggle(User $user, Plan $plan): bool
    {
        if ($user->isAdmin()) {
            return true;
        }

        $exists = $plan->users->filter(function ($val) use ($user, $plan) {
            return $user->id === $val->id && $user->id !== $plan->user_id;
        });

        return $exists->isNotEmpty();
    }
}
